package com.dc.di.sf.dt;

import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;

import com.dc.di.sf.dt.convertor.TransObjectConvertor;
import com.dc.di.sf.utils.OMUtils;
import com.dc.trans.steps.datapack.DataPackData;

/**
* @ClassName: XMLMessageCreaterImpl
* @Description: TODO
* @author zhangbinp
* @date Dec 15, 2011 9:47:37 AM
*/
public class XMLMessageConvertImpl implements MessageConvertInterface {

	public void addMessageHeader(DataPackData data , StringBuilder pack) {
		pack.setLength(0);
		pack.append(OMUtils.generateOMElementBeginString(BusinessData.TAG_BUSINESSDATA, Constants.NAMESPACE_CNEGD_PREFIX, Constants.NAMESPACE_CNEGD_URL));
		pack.append(data.dataStructureString);
		pack.append(OMUtils.generateOMElementBeginString(DataSet.TAG_DATASET));
	}

	public void completeMessage(StringBuilder pack) {
		pack.append(OMUtils.generateOMElementEndString(DataSet.TAG_DATASET));
		pack.append(OMUtils.generateOMElementEndString(BusinessData.TAG_BUSINESSDATA));
	}

	public String createDataStructure(RowMetaInterface rowMeta) {
		if (rowMeta == null)
			return null;
		DataStructure dataStructure = new DataStructure();
		for (ValueMetaInterface valueMeta : rowMeta.getValueMetaList())
			dataStructure.addDataUnit(convertValueMetaToDataUnit(valueMeta));
		return dataStructure.toXMLString();
	}

	public static DataUnit convertValueMetaToDataUnit(ValueMetaInterface valueMeta) {
		DataUnit dataUnit = new DataUnit();
		dataUnit.setIdName(valueMeta.getName());
		switch (valueMeta.getType()) {
		case ValueMetaInterface.TYPE_STRING:
			dataUnit.setDataType(DataUnit.TYPE_STRING);
			break;
		case ValueMetaInterface.TYPE_BIGNUMBER:
			dataUnit.setDataType(DataUnit.TYPE_DECIMAL);
			break;
		case ValueMetaInterface.TYPE_DATE:
			dataUnit.setDataType(DataUnit.TYPE_DATETIME);
			break;
		case ValueMetaInterface.TYPE_BINARY:
			dataUnit.setDataType(DataUnit.TYPE_BINARY);
			break;
		case ValueMetaInterface.TYPE_INTEGER:
			dataUnit.setDataType(DataUnit.TYPE_INTEGER);
			break;
		case ValueMetaInterface.TYPE_NUMBER:
			dataUnit.setDataType(DataUnit.TYPE_NUMBER);
			break;
		}
		return dataUnit;
	}
	
	public void writeRowToMessage(DataPackData data, StringBuilder pack, Object[] rowData,
			Object routeData) {
		RecordData rd = TransObjectConvertor.convertRowDataToRecordData(data.dataStructure, rowData);
		pack.append(rd.toXMLString());
		if (data.packDataCountMap.get(routeData)==null) {
			data.packDataCountMap.put(routeData, 1L);
		} else {
			long l = data.packDataCountMap.get(routeData);
			data.packDataCountMap.put(routeData, ++l);
		}
	}
}
